//
//  VideoChatTableCell.swift
//  GameForum
//
//  Created by Vill on 2022/10/12.
//

import UIKit

class VideoChatTableCell: UITableViewCell {
    
    @IBOutlet weak var bgView: UIView!
    
    @IBOutlet weak var nameLbl: UILabel!
    
    @IBOutlet weak var contentLbl: UILabel!
    
    @IBOutlet weak var bgViewWidthCos: NSLayoutConstraint!
    
    @IBOutlet weak var contentWidthCons: NSLayoutConstraint!
    
    static let reusedID = "VideoChatTableCell"
    public func cellWithTableView(_ tableView:UITableView) -> VideoChatTableCell{
        var cell:VideoChatTableCell! = tableView.dequeueReusableCell(withIdentifier: VideoChatTableCell.reusedID) as? VideoChatTableCell
        if cell == nil {
            cell = (Bundle.main.loadNibNamed("VideoChatTableCell", owner: nil, options: nil)?.first as! VideoChatTableCell)
        }
        return cell!
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        self.bgView.layer.cornerRadius = 20
        self.bgView.layer.masksToBounds = true
        self.bgView.backgroundColor = UIColor.colorWithHex("#1E1E1E",  0.4)
        self.contentLbl.font = UIFont.pingfangFont(ofSize: 13, weight: .bold)
        self.nameLbl.font = UIFont.pingfangFont(ofSize: 15, weight: .medium)
        self.contentLbl.textColor = .white
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
    func update(_ log: Log) {
        self.nameLbl.textColor = log.type.txtColor
        self.nameLbl.text = "\(log.nickName):"
        self.contentLbl.text = "\(log.content)"
            
        let nickNameSize = VideoChatTableCell.getTextLabelSize(message: log.nickName, width: PTW(200), font: UIFont.pingfangFont(ofSize: 13, weight: .bold))
        let contentSize = VideoChatTableCell.getTextLabelSize(message: log.content, width: PTW(260) - nickNameSize.width, font: UIFont.pingfangFont(ofSize: 15, weight: .medium))
        let maxWidth =  nickNameSize.width + contentSize.width + PTW(40)
        bgViewWidthCos.constant =  maxWidth >= PTW(300) ? PTW(300) : maxWidth
        contentWidthCons.constant = contentSize.width
    }
    
    // 获取文本size
    class func getTextLabelSize(message: String, width: CGFloat,font:UIFont) -> CGSize {
        guard !message.isEmpty else { return .zero }
        // 最大宽度为
        let textRect = (message as NSString)
            .boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)),
                          options: [.usesLineFragmentOrigin],
                          attributes: [NSAttributedString.Key.font: font],
                          context: nil)
        return CGSize(width: textRect.size.width, height: textRect.size.height)
    }
    
}
